﻿package com.kingtone.rongji;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.kingtone.rongji.biz.Address;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class ReceiveAddressActivity extends BaseActivity {

	private TextView title = null;
	private ImageView backBtn = null;
	private ImageView leftIcon = null;
	private TextView rightTitle = null;
	private Button addAddressBtn = null;
	private ListView addressList = null;
	private AddressAdapter addAdapter = null;
	private Context context = ReceiveAddressActivity.this;
	private int pageFlag;
	private int tempShippingId = 0;
	HashMap<String, Boolean> states = new HashMap<String, Boolean>();
	private ViewHolder holder = null;
	private boolean isFirst = true;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_receive_address);
		setupView();
		getShippingAddress(false);
		pageFlag = getIntent().getIntExtra("pageFlag", 0);
	}
	
	private void setupView()
	{
		title = (TextView)findViewById(R.id.title);
		title.setText(getString(R.string.receive_address));
		rightTitle =(TextView)findViewById(R.id.right_title);
		rightTitle.setText(getString(R.string.receive_address));
		
		leftIcon = (ImageView)findViewById(R.id.left_icon);
		leftIcon.setBackgroundResource(R.drawable.icon_zhi);
		
		addAddressBtn = (Button)findViewById(R.id.add_receive_address);
		//add address
		addAddressBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				Intent intent = new Intent(ReceiveAddressActivity.this, AddAddressActivity.class);
				intent.putExtra("flag", AppContasts.TO_ADD_ADDRESS);
				intent.putExtra("isDefault", 1);
				startActivityForResult(intent, 100);
			}
		});
		
		addressList = (ListView)findViewById(R.id.address_list);
		//点击设置为默认地址
		addressList.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				
			}
		});
		
		backBtn = (ImageView)findViewById(R.id.back);
		backBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				onBackPressed();
			}
		});
	}
	
	/**
	 * 获取收货地址列表
	 */
	private void getShippingAddress(final boolean needBack)
	{
		String userId = SharedPreferencesUtil.getInstance(context).getString(AppContasts.USERID_KEY);
		RongJiRestClient.getShippingAddress(userId, "0", new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				RongJiUtils.showEmptyProgress(context);
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				 if(arg2 != null)
				 {
				    String filureStr = new String(arg2);
					Log.d("failure", filureStr);
				 }
				RongJiUtils.dismissProgress();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				
				RongJiUtils.dismissProgress();
				
				if(arg2 != null && !new String(arg2).equalsIgnoreCase("null"))
				{
					String result = new String(arg2);
					Gson gson = new Gson();
					JsonParser parser = new JsonParser();
					JsonElement element = parser.parse(result);
					if(element instanceof JsonArray)
					{
						JsonArray array = parser.parse(result).getAsJsonArray();
						ArrayList<Address> list = new ArrayList<Address>();
						for(JsonElement obj:array) {
							Address object = gson.fromJson(obj, Address.class);
							list.add(object);
						}
						
						if(needBack) {
							for(Address item : list) {
								if(null != item && item.IsDefault.equals("true")) {
									Intent intent = new Intent(ReceiveAddressActivity.this, OrderSummitActivity.class);
									intent.putExtra("defaultAddress", item);
									setResult(RESULT_OK, intent);
									finish();
								}
							}
						} else {
							addAdapter = new AddressAdapter(context, list);
							addressList.setAdapter(addAdapter);
							addAdapter.notifyDataSetChanged();
						}
					}
				}
			}	
		});
	}
	
	
   class AddressAdapter extends BaseAdapter
	{
		private Context context = null;
		private ArrayList<Address> addList = null;
		private LayoutInflater inflater; 

		public AddressAdapter(Context context, ArrayList<Address> addList)
		{
			this.inflater=LayoutInflater.from(context);
			this.context = context;
			this.addList = addList;
		}
		
		public List<Address> getData() {
			return addList;
		}
		
		@Override
		public int getCount()
		{
			return addList.size();
		}

		@Override
		public Object getItem(int position)
		{
			return addList.get(position);
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent)
		{
			 View view;
			 Address address = addList.get(position);
			//如果已加载过，使用缓存技术不再重新加载
			if(convertView!=null){
				view=convertView;
				holder=(ViewHolder) view.getTag();
			}else{
				view=inflater.inflate(R.layout.address_item, null);
				holder = new ViewHolder();
				holder.linearLayout =(LinearLayout)view.findViewById(R.id.text_layout);
				holder.isDefault = (RadioButton)view.findViewById(R.id.add_is_default);
				holder.addNamePhone = (TextView) view.findViewById(R.id.address_name_phone);
				holder.addArea =(TextView) view.findViewById(R.id.address_area);
				holder.addDetail =(TextView) view.findViewById(R.id.address_detail);
				holder.addEdit = (ImageView)view.findViewById(R.id.address_modify);
				holder.addDel = (ImageView)view.findViewById(R.id.address_delete);
			}
			holder.addEdit.setTag(position);
			holder.addEdit.setOnClickListener(new View.OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					Intent intent = new Intent(ReceiveAddressActivity.this, AddAddressActivity.class);
					intent.putExtra("flag", AppContasts.TO_MDOFY_ADDRESS);
					Address tempAdd = addList.get((Integer)v.getTag());
					intent.putExtra("address", tempAdd);
					intent.putExtra("isDefault", 1);
					startActivityForResult(intent, 100);
				}
			});
			holder.addDel.setTag(position);
			holder.addDel.setOnClickListener(new View.OnClickListener()
			{
				
				@Override
				public void onClick(View v)
				{
					Address tempAdd = addList.get((Integer)v.getTag());
					if(tempAdd != null)
					{
						tempShippingId = tempAdd.getShippingId();
					}
					new AlertDialog.Builder(context).setTitle(R.string.confirm_del_address)
					.setPositiveButton(R.string.btn_confirm, new DialogInterface.OnClickListener()
					{
						public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
						{
							
							delShipingAddress(tempShippingId);
							
						}
					}).setNegativeButton(R.string.btn_cancel, null).show();
				}
			});
			view.setTag(holder);
			
			if(pageFlag == 1) holder.isDefault.setVisibility(View.GONE);
			
			holder.isDefault.setId(position);
			holder.isDefault.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					Address add = addList.get(v.getId());
					if(add != null)
					{
						 for (String key : states.keySet()) 
						 {
					          states.put(key, false);
					     }
					     states.put(String.valueOf(v.getId()), true);
					     isFirst = false;
					     AddressAdapter.this.notifyDataSetChanged();
					        
						setDefaultShipingAddress(add);
					}
				}
			});
			
			holder.linearLayout.setId(position);
			holder.linearLayout.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					Address add = addList.get(v.getId());
					if(add != null)
					{
						 for (String key : states.keySet()) 
						 {
					          states.put(key, false);
					     }
					     states.put(String.valueOf(v.getId()), true);
					     isFirst = false;
					     AddressAdapter.this.notifyDataSetChanged();
					        
						setDefaultShipingAddress(add);
					}
				}
			});
			
			boolean res = false;
		    if (states.get(String.valueOf(position)) == null
		        || states.get(String.valueOf(position)) == false) {
		      res = false;
		      states.put(String.valueOf(position), false);
		    } else
		      res = true;

		    holder.isDefault.setChecked(res);
		    if(isFirst)
			{
				if(address.IsDefault.equals("true"))
				{
					holder.isDefault.setChecked(true);
				}else
				{
					holder.isDefault.setChecked(false);
				}
			}
			holder.addNamePhone.setText(address.getShipTo() + " " +address.getCellPhone());
			holder.addArea.setText(address.getRegionAddress());
			holder.addDetail.setText(address.getAddress());
			
			return view;
		}
		
		/**
		 * 删除收货地址
		 * @param shipingId
		 */
		private void delShipingAddress(int shippingId)
		{
			RongJiRestClient.delShipingAddress(shippingId, new AsyncHttpResponseHandler() {

				@Override
				public void onStart() {
					RongJiUtils.showEmptyProgress(context);
				}
				
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					RongJiUtils.dismissProgress();
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					RongJiUtils.dismissProgress();
					
					if(arg2 != null && !new String(arg2).equalsIgnoreCase("null"))
					{
						/*String result = new String(arg2);
	                    if(result.equals("\"0\""))
	                    {
	                    	getShippingAddress();
	                    }else
	                    {
	                    	Toast.makeText(context, "删除收货地址失败", Toast.LENGTH_SHORT).show();
	                    }*/
						getShippingAddress(false);
					}
				}	
			});
		}
	}
   
   private void setDefaultShipingAddress(final Address address)
	{
		String userId = SharedPreferencesUtil.getInstance(context).getString(AppContasts.USERID_KEY);
		String shipTo = address.getShipTo();
		String cellPhone = address.getCellPhone();
		String add = address.getAddress();
		String zipCode = address.getZipcode();
		int countyRegionId = address.getRegionId();
		int shippingId = address.getShippingId();
		RongJiRestClient.createOrUpdateShipingAddress(userId, shipTo, cellPhone, countyRegionId, add, zipCode, shippingId, AppContasts.TO_MDOFY_ADDRESS, 1, new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				RongJiUtils.showEmptyProgress(context);
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				String result = new String(arg2);
				Log.d("createShipingAddress failure ", result);
				RongJiUtils.dismissProgress();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				RongJiUtils.dismissProgress();
				
				if(arg2 != null && !new String(arg2).equalsIgnoreCase("null"))
				{
					String result = new String(arg2);
					JSONTokener jsonParser = new JSONTokener(result);  
				    try {
						JSONObject add = (JSONObject) jsonParser.nextValue();
						boolean errorCode = add.optBoolean("Status");
						if(errorCode)
						{
							Intent intent = new Intent(ReceiveAddressActivity.this, OrderSummitActivity.class);
							intent.putExtra("defaultAddress", address);
							setResult(RESULT_OK, intent);
							finish();
						}else
						{
							String errorMsg = add.optString("ErrorMessage");
							if(!TextUtils.isEmpty(errorMsg))
							{
								Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
							}
						}
						
				    } catch (JSONException e) {
						e.printStackTrace();
					} 
				}
			}	
		});
	}
   
   private class ViewHolder
	{
	    public LinearLayout linearLayout;
	    public RadioButton isDefault;
		public TextView addNamePhone;
		public TextView addArea;
		public TextView addDetail;
		public ImageView addEdit;
		public ImageView addDel;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==100 && resultCode==RESULT_OK) {
			getShippingAddress(true);
		}
	}
   
}
